package com.example.basecommon.base;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.example.basecommon.R;
import com.example.basecommon.R2;
import com.example.basecommon.http.RequestErrorHelper;
import com.example.basecommon.utils.ScannerDialog;
import com.example.basecommon.utils.TipsNormalDialog;

import java.util.Arrays;

import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author dlj
 * des：
 */
public abstract class BaseActivity extends AppCompatActivity {

    public RequestErrorHelper requestErrorHelper;
    private EditText editText;
    private String mTagText = "";
    private NfcAdapter mNfcAdapter;
    private PendingIntent mPendingIntent;

//    @OnClick(R2.id.back)
//    void onBack() {
//        finish();
//    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //隐藏状态栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        if (Build.VERSION.SDK_INT >= 21) {
            Window window = getWindow();
            //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //设置状态栏颜色
            window.setStatusBarColor(getResources().getColor(R.color.base_header));
        }
        //设置布局
        setContentView(R.layout.activity_baseactivity);
        //设置横屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        FrameLayout content = (FrameLayout) findViewById(R.id.base_content);
        LayoutInflater.from(this).inflate(initLayout(), content, true);
        //绑定ButterKnife
        ButterKnife.bind(this);
        //设置控件
        initView();
        requestErrorHelper = new RequestErrorHelper(this);
    }

    /**
     * 设置布局
     *
     * @return
     */
    public abstract int initLayout();

    /**
     * 初始化view
     *
     * @return
     */
    public abstract void initView();

    /**
     * 是否设置标题栏
     *
     * @return
     */
    public void setTitle(boolean isShowTitle, String title) {
//        if (isShowTitle) {
//            findViewById(R.id.title).setVisibility(View.VISIBLE);
//            TextView tv_title = findViewById(R.id.activity_title_text);
//            tv_title.setText(title);
//        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        //一旦截获NFC消息，就会通过PendingIntent调用窗口
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()), 0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (requestErrorHelper != null) {
            requestErrorHelper.resume();
        }

        //设置处理优于所有其他NFC的处理
        if (mNfcAdapter != null)
            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
    }

    @Override
    protected void onPause() {
        if (requestErrorHelper != null) {
            requestErrorHelper.pause();
        }
        //恢复默认状态
        if (mNfcAdapter != null)
            mNfcAdapter.disableForegroundDispatch(this);
        super.onPause();
    }

    /**
     * 设置扫码监听
     *
     * @param editText
     */
    public void setEditTextScannerEvents(final EditText editText, View.OnKeyListener listener) {
        editText.setOnLongClickListener(v -> {
            new ScannerDialog(BaseActivity.this,
                    result -> {
                        if (!TextUtils.isEmpty(result)) {
                            editText.setText(result);
                            editText.selectAll();
                            editText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER));
                        }
                    }).config().show(v);
            return false;
        });
        editText.setOnKeyListener(listener);
//        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View view, boolean b) {
//                if (b) {
//                    BaseActivity.this.editText = editText;
//                }
//            }
//        });
    }

    /**
     * 隐藏输入法软键盘
     */
    public void hideIME(EditText view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * @return 获取activity 类名
     */
    public String getActivityClassName() {
        return getClass().getName();
    }

    public String getActivityFullName() {
        return getClass().getPackage().getName();
    }

    public View getDecorView() {
        return getWindow().getDecorView();
    }

    private long firstTime = 0;

    /**
     * 双击弹框提示是否退出应用
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                //如果两次按键时间间隔大于2秒，则不退出
                //Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = secondTime;//更新firstTime
            } else {
                //两次按键小于2秒时，弹框提示是否退出应用。点击确认退出应用
                TipsNormalDialog tipsNormalDialog = new TipsNormalDialog();
                tipsNormalDialog.showOnClick(this, "退出提示", "是否退出当前应用");
                tipsNormalDialog.setOnOKClickListener(() -> System.exit(0));
            }
            return true;
        }

        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        requestErrorHelper.destroy();
        super.onDestroy();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        try {
            //当该Activity接收到NFC标签时，运行该方法
            //1.获取Tag对象
            Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            //2.获取Ndef的实例
            Ndef ndef = Ndef.get(detectedTag);
            readNfcTag(intent);
            editText.setText(mTagText);
            editText.selectAll();
            editText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取NFC标签文本数据
     */
    private void readNfcTag(Intent intent) {
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
                    NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage msgs[] = null;
            int contentSize = 0;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                    contentSize += msgs[i].toByteArray().length;
                }
            }
            try {
                if (msgs != null) {
                    NdefRecord record = msgs[0].getRecords()[0];
                    String textRecord = parseTextRecord(record);
                    mTagText = textRecord;
                }
            } catch (Exception e) {
            }
        }
    }

    /**
     * 解析NDEF文本数据，从第三个字节开始，后面的文本数据
     *
     * @param ndefRecord
     * @return
     */
    public static String parseTextRecord(NdefRecord ndefRecord) {
        /**
         * 判断数据是否为NDEF格式
         */
        //判断TNF
        if (ndefRecord.getTnf() != NdefRecord.TNF_WELL_KNOWN) {
            return null;
        }
        //判断可变的长度的类型
        if (!Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
            return null;
        }
        try {
            //获得字节数组，然后进行分析
            byte[] payload = ndefRecord.getPayload();
            //下面开始NDEF文本数据第一个字节，状态字节
            //判断文本是基于UTF-8还是UTF-16的，取第一个字节"位与"上16进制的80，16进制的80也就是最高位是1，
            //其他位都是0，所以进行"位与"运算后就会保留最高位
            String textEncoding = ((payload[0] & 0x80) == 0) ? "UTF-8" : "UTF-16";
            //3f最高两位是0，第六位是1，所以进行"位与"运算后获得第六位
            int languageCodeLength = payload[0] & 0x3f;
            //下面开始NDEF文本数据第二个字节，语言编码
            //获得语言编码
            String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
            //下面开始NDEF文本数据后面的字节，解析出文本
            String textRecord = new String(payload, languageCodeLength + 1,
                    payload.length - languageCodeLength - 1, textEncoding);
            return textRecord;
        } catch (Exception e) {
            throw new IllegalArgumentException();
        }
    }
}
